package com.goldsprite.microhorigame.screens.tests.lightsystem;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;

public class AdvancedSpriteBatch extends SpriteBatch {
	private Texture extraTexture;
	private int extraTextureUnit = 1;
	private ShaderProgram myShader;

	public AdvancedSpriteBatch() {
		super();
		myShader = createMultiTextureShader();
	}

	public void setExtraTexture(Texture extraTexture) {
		this.extraTexture = extraTexture;
	}

	@Override
	public void begin() {
		// 关键：禁用严格模式！
		ShaderProgram.pedantic = false;

		super.begin();
		setShader(myShader);

		if (extraTexture != null) {
			getShader().setUniformi("u_lightDataTexture", 1);
			extraTexture.bind(1);
			extraTexture.bind(0);
		}
	}

	@Override
	public void end() {
		setShader(null);
		super.end();
	}

	private ShaderProgram createMultiTextureShader() {
		// 顶点着色器 - 使用文本块
		String vertexShader = """
				#version 300 es
				in vec4 a_position;
				in vec4 a_color;
				in vec2 a_texCoord0;
				in vec2 a_texCoord1;
				uniform mat4 u_projTrans;
				out vec4 v_color;
				out vec2 v_texCoord0;
				out vec2 v_texCoord1;
				void main() {
				    v_color = a_color;
				    v_texCoord0 = a_texCoord0;
				    v_texCoord1 = a_texCoord1;
				    gl_Position = u_projTrans * a_position;
				}
				""";

		// 片段着色器 - 使用文本块
		String fragmentShader = """
				#version 300 es
				precision mediump float;
				in vec4 v_color;
				in vec2 v_texCoord0;
				in vec2 v_texCoord1;
				out vec4 fragColor;
				uniform sampler2D u_texture;           // 单元0 - SpriteBatch自动管理
				uniform sampler2D u_lightDataTexture;  // 单元1 - 手动管理
				void main() {
				    vec4 mainColor = texture(u_texture, v_texCoord0) * v_color;
				    vec4 lightData = texture(u_lightDataTexture, v_texCoord0) * v_color;

				    // 测试2：分区显示
					if (v_texCoord0.x < 0.5) {
						fragColor = mainColor;           // 左边显示主纹理
					} else {
						fragColor = lightData;           // 右边显示光照纹理
					}

//				    fragColor = vec4(vec3(1.0), mainColor.a);
				}
				""";

		ShaderProgram shader = new ShaderProgram(vertexShader, fragmentShader);

		if (!shader.isCompiled()) {
			Gdx.app.error("SHADER", "Compilation failed: " + shader.getLog());
		} else {
			Gdx.app.log("SHADER", "Multi-texture shader compiled successfully");
		}

		return shader;
	}
}
